<?php

App::uses('Shell', 'Console');
App::uses('BaseParser', 'Console/Command/Task');

class LeituraHS02Task extends BaseParser {
    public $uses = array('LeiturasHs02');

    public function execute() {
        $this->out('LeituraHS02');

        $this->parse();
    }

    private function parse() {
        $contSeparate = 0;
        $this->content = explode("\n", $this->content);

        $db = $this->LeiturasHs02->getDataSource();
        $db->begin();
    
        foreach ($this->content as $line) {
            if ($contSeparate < 3) {
                if ($line[0] == '-')
                    $contSeparate++;

                continue;
            }

            $line = trim($line);
            $line = str_replace(',','.',$line);
            $itens = preg_split("/  +/", $line);

            if (count($itens) < 6)
                continue;

            $date = $this->convertToDateSql($itens[0]);

            $sequencia = $this->getNumSequencia($date);

            $leitura = array(
                'LeiturasHs02' => array(
                    'sequencia'     => $sequencia,
                    'hora'          => $date,
                    'estacao_id'    => $this->estacaoId,
                    'precipitacao'  => $itens[1],
                    'canal1'        => $itens[2],
                    'nivel'         => $itens[3],
                    'vazao'         => $itens[4],
                    'tensao'        => $itens[5],
                    'canal2'        => @$itens[6]
                )
            );

            if (!$this->LeiturasHs02->save($leitura)) {
                $this->out('Erro ao adicionar Leitura, erros: '.print_r($this->LeiturasHs02->validationErrors, true));
            }       
        }
        
        if ($db->commit() === false) {
            $this->out('Erro ao adicionar Leitura, erros: '.print_r($this->LeiturasHs02->validationErrors, true));
        }
    }
}